package com.tensequare.manager.interceptor;

import common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Feng.Wang
 * @Company: Zelin.ShenZhen
 * @Description: 定义过滤器用于拦截每个控制器方法
 * @Date: Create in 2019/3/28 16:53
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到Authorization这个请求头
        String header = request.getHeader("Authorization");
        //2.判断
        if(header != null && header.startsWith("Bearer ")){
            //2.1)得到token的值
            String token = header.substring(7);
            //2.2)得到claims
            Claims claims = jwtUtil.parseJWT(token);
            //2.3)判断权限
            String roles = (String) claims.get("roles");
            //2.4)根据角色放不同的key到request作用域中
            if("admin".equals(roles)){
                request.setAttribute("admin_claims",claims);
            }else if("user".equals(roles)){
                request.setAttribute("user_claims",claims);
            }
        }
        return true;
    }
}
